package chan.project.aimodule.controller;

import chan.project.aimodule.Service.DailyConsultationService;
import chan.project.aimodule.Service.MessageProducer;
import chan.project.aimodule.Service.MessageProducerKafka;
import chan.project.aimodule.Service.TextParseService;
import chan.project.smartlawmodel.dto.ai.DailyConsultationVo;
import chan.project.smartlawmodel.dto.ai.TextParseRequest;
import chan.project.smartlawmodel.dto.common.LawSuit;
import chan.project.smartlawmodel.dto.data.LegalCase;
import chan.project.smartlawmodel.dto.instrument.InstrumentMessage;
import chan.project.smartlawmodel.dto.lawregulation.LawRegulationMessage;
import chan.project.smartlawmodel.entity.Instrument;
import chan.project.smartlawmodel.entity.LawRegulation;
import chan.project.smartlawmodel.vo.LegalCaseVo;
import chan.project.smartlawservice.AiService.AiFeignClient;
import chan.project.smartlawservice.dataManage.DataManageFeignClient;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/AI/inner")
public class AiControllerInner implements AiFeignClient {

    @Resource
    private DailyConsultationService dailyConsultationService;

    @Resource
    private DataManageFeignClient dataManageFeignClient;

    @Resource
    private TextParseService textParseService;

    @Resource
    private MessageProducerKafka messageProducerKafka;

    @Resource(name = "kafkaSendExecutor")
    private Executor kafkaSendExecutor;
    /**
     * 日常调用接口
     * @param message
     * @return
     */
    @Override
    @GetMapping("/daily")
    //注：spring boot3 默认不支持@RequestParam注解，需要手动添加@RequestParam注解
    public DailyConsultationVo dailyPrompt(@RequestParam("message") String message) {
        DailyConsultationVo s = dailyConsultationService.askQuestion(message);
        System.out.println(s);
        return s;
    }


    /**
     * 解析法律文本并返回结果
     * @param textParseRequest
     */
    @Override
    @PostMapping("/parse")
    public Flux<String> parseText(@RequestBody TextParseRequest textParseRequest) {
        Flux<String> stringFlux = textParseService.parseText(textParseRequest);

        // 如果你需要对每个 ChatResponse 进行一些处理，比如打印日志
        return stringFlux.doOnNext(chatResponse -> {
                    System.out.print(chatResponse);
                }).doOnError(error -> log.error("文件分析失败", error))
                .doOnComplete(() -> log.info("文件分析完成"));
    }

    /**
     * 诉讼模拟器接口
     * @return
     */
    @Override
    @PostMapping("/litigationSimulator")
    public LegalCaseVo litigationSimulator(@RequestBody LegalCase legalCase) {
        String reason = legalCase.getReason();
        String plaintiffDescription = legalCase.getPlaintiffDescription();
        String defendantDescription = legalCase.getDefendantDescription();
        String courtName = legalCase.getCourtName();
        //根据案例模拟出胜诉率
        ArrayList<String> keywords = new ArrayList<>();
        keywords.add(reason);
        keywords.add(plaintiffDescription);
        keywords.add(defendantDescription);
        keywords.add(courtName);
        //查询出参考案件列表与法律参考列表
        List<LawRegulation> lawRegulations = dailyConsultationService.messageToLaw(reason);
        List<Instrument> allLegalCase = dataManageFeignClient.getLegalCase(keywords);
        //传输法律法规与调用时间
        sendAnalysisMessages(lawRegulations, allLegalCase, Date.from(Instant.now()));
        //诉讼分析请求
        LawSuit lawSuit = dailyConsultationService.litigationSimulator(legalCase, lawRegulations, allLegalCase);
        LegalCaseVo legalCaseVo = new LegalCaseVo();
        BeanUtils.copyProperties(lawSuit, legalCaseVo);
        //只封装法律名称与案例名称
        List<String> literatures = (CollectionUtil.isEmpty(lawRegulations))?new ArrayList<>():lawRegulations.stream().map(LawRegulation::getTitle).collect(Collectors.toList());
        List<String> legalCases = (CollectionUtil.isEmpty(allLegalCase))?new ArrayList<>():allLegalCase.stream().map(Instrument::getTitle).collect(Collectors.toList());
        legalCaseVo.setLiteratures(literatures);
        legalCaseVo.setCases(legalCases);
        return legalCaseVo;
    }

    /**
     * 诉讼分析消息发送逻辑
      */
    private void sendAnalysisMessages(List<LawRegulation> lawRegulations,
                                      List<Instrument> instruments,
                                      Date timestamp) {
        kafkaSendExecutor.execute(() -> {
            try {
                List<InstrumentMessage> instrumentMessages = instruments.stream()
                        .map(inst -> InstrumentMessage.toInstrumentMessage(inst, timestamp))
                        .collect(Collectors.toList());

                List<LawRegulationMessage> lawMessages = lawRegulations.stream()
                        .map(lr -> LawRegulationMessage.toLawRegulationMessage(lr, timestamp))
                        .collect(Collectors.toList());

                messageProducerKafka.sendLegalMessage(JSONUtil.toJsonStr(lawMessages));
                messageProducerKafka.sendInstrumentMessage(JSONUtil.toJsonStr(instrumentMessages));
            } catch (Exception e) {
                log.warn("发送分析消息失败", e);
            }
        });
    }

    /**
     * 正常传入问题调用
     * @param textParseRequest
     * @return
     */
    @PostMapping("/parseByNormal")
    public String parseTextNormal(@RequestBody TextParseRequest textParseRequest) {
        return textParseService.parseTextNormal(textParseRequest);
    }

}
